// import axios from 'axios'
import Dialog from 'vant/lib/dialog'
import {getToken} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/', // api 的 base_url
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken()
    config.headers['Content-Type'] = 'application/json'
    config.headers['Accept'] = 'application/json'
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Dialog.alert({message: '200-300错误'})
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        Dialog.alert({message: '网络请求超时，请稍后再试'})
        return Promise.reject(error)
      }
    }
    if (code) {
      if (code === 401) {
        Dialog.alert({message: '登陆已过期，请重新登录'})
        .then(() => {
          wx.miniProgram.redirectTo({url: '/pages/login'})
        })
      } else if (code === 403) {
        Dialog.alert({message: '403:没有权限访问，请咨询技术中心'})
        // router.push({ path: '/401' })
      } else {
        const errorMsg = error.response.data.message
        if (errorMsg !== undefined) {
          Dialog.alert({message: errorMsg})
        }
      }
    } else {
      Dialog.alert({message: '服务器内部错误，请联系技术中心处理'})
    }
    return Promise.reject(error)
  }
)
export default service
